package com.jin.controller;

import com.jin.common.Result;
import com.jin.model.dto.UserInfoResponse;
import com.jin.model.dto.UserUpdateRequest;
import com.jin.service.UserService;
import com.jin.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    public UserController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<UserInfoResponse> getUserInfo(HttpServletRequest request) {
        try {
            // 从请求头中获取用户ID
            Long userId = getCurrentUserId(request);

            UserInfoResponse userInfo = userService.getUserInfo(userId);

            log.info("Get user info successful for userId: {}", userId);
            return Result.success("获取用户信息成功", userInfo);

        } catch (Exception e) {
            log.error("Get user info failed", e);
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<UserInfoResponse> updateUserInfo(
            @Validated @RequestBody UserUpdateRequest request,
            HttpServletRequest httpRequest) {
        try {
            // 从请求头中获取用户ID
            Long userId = getCurrentUserId(httpRequest);

            UserInfoResponse userInfo = userService.updateUserInfo(userId, request);

            log.info("Update user info successful for userId: {}", userId);
            return Result.success("更新用户信息成功", userInfo);

        } catch (Exception e) {
            log.error("Update user info failed", e);
            return Result.error("更新用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证令牌");
        }

        String token = authHeader.substring(7);
        return jwtUtil.getUserIdFromToken(token);
    }
}
